package com.maserb.monitor.wechat;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class WeChatAccessToken {

	private String ACCESS_TOKEN = "";
	/**生命周期：默认2小时*/
	private long EXPIRES_IN = 60*60*2;
	/**刷新时间*/
	private long REFRESH_TIME = 0;
	
	private String JS_TICKET = "";
	/**生命周期：默认2小时*/
	private long JS_TICKET_EXPIRES_IN = 60*60*2;
	/**刷新时间*/
	private long JS_TICKET_REFRESH_TIME = 0;

	@Autowired
	WeChatAccessTokenTask weChatAccessTokenTask;

	public void init(){
		if(StringUtils.isEmpty(ACCESS_TOKEN) || isRefreshTimeOut()){
			weChatAccessTokenTask.getInstance().begin();
		}
	}
	
	public String getAccessToken() {
		if(StringUtils.isEmpty(ACCESS_TOKEN) || isRefreshTimeOut()){
			init();
		}
		return ACCESS_TOKEN;
	}

	public void setAccessToken(String aCCESSTOKEN) {
		ACCESS_TOKEN = aCCESSTOKEN;
	}

	public long getExpiresIn() {
		return EXPIRES_IN;
	}

	public void setExpiresIn(long eXPIRESIN) {
		EXPIRES_IN = eXPIRESIN;
		REFRESH_TIME = System.currentTimeMillis();
	}
	
	public boolean isRefreshTimeOut(){
		if((System.currentTimeMillis() - REFRESH_TIME)/1000 >= EXPIRES_IN){
			return true;
		}
		return false;
	}
	
	public String getJsTicket() {
		if(StringUtils.isEmpty(JS_TICKET) || isJsTicketRefreshTimeOut()){
			if(StringUtils.isEmpty(ACCESS_TOKEN) || isRefreshTimeOut()){
				weChatAccessTokenTask.getInstance().begin();
			}else{
				weChatAccessTokenTask.getInstance().getJsTicket();
			}
		}
		return JS_TICKET;
	}

	public void setJsTicket(String jsTicket) {
		JS_TICKET = jsTicket;
	}

	public long getJsTicketExpiresIn() {
		return JS_TICKET_EXPIRES_IN;
	}

	public void setJsTicketExpiresIn(long expiresin) {
		JS_TICKET_EXPIRES_IN = expiresin;
		JS_TICKET_REFRESH_TIME = System.currentTimeMillis();
	}
	
	public boolean isJsTicketRefreshTimeOut(){
		if((System.currentTimeMillis() - JS_TICKET_REFRESH_TIME)/1000 >= JS_TICKET_EXPIRES_IN){
			return true;
		}
		return false;
	}

}
